package com.erp.gather.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Dict;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.gather.api.domain.ErpCollectProductSkuPrice;
import com.erp.gather.domain.dto.SkuInventory;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.gather.api.domain.ErpSellerStoreProductSku;
import com.erp.gather.domain.bo.ErpSellerStoreProductSkuBo;
import com.ruoyi.gather.api.domain.QueryProductParam;
import com.erp.gather.domain.vo.ErpSellerStoreProductSkuVo;
import com.erp.gather.mapper.ErpSellerStoreProductExpandMapper;
import com.erp.gather.mapper.ErpSellerStoreProductSkuMapper;
import com.erp.gather.service.IErpCollectProductSkuPriceService;
import com.erp.gather.service.IErpSellerStoreProductSkuService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.utils.JsonUtils;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.gather.api.domain.ErpSellerStoreProductExpand;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * 卖家在线商品SKU;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）Service业务层处理
 *
 * @author erp
 * @date 2023-03-28
 */
@RequiredArgsConstructor
@Service
public class ErpSellerStoreProductSkuServiceImpl implements IErpSellerStoreProductSkuService {

    private final ErpSellerStoreProductSkuMapper baseMapper;
    private final ErpSellerStoreProductExpandMapper productExpandMapper;
    private final IErpCollectProductSkuPriceService productSkuPriceService;

    /**
     * 查询卖家在线商品SKU;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）
     */
    @Override
    public ErpSellerStoreProductSkuVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询卖家在线商品SKU;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）列表
     */
    @Override
    public TableDataInfo<ErpSellerStoreProductSkuVo> queryPageList(ErpSellerStoreProductSkuBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpSellerStoreProductSku> lqw = buildQueryWrapper(bo);
        Page<ErpSellerStoreProductSkuVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询卖家在线商品SKU;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）列表
     */
    @Override
    public List<ErpSellerStoreProductSkuVo> queryList(ErpSellerStoreProductSkuBo bo) {
        LambdaQueryWrapper<ErpSellerStoreProductSku> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpSellerStoreProductSku> buildQueryWrapper(ErpSellerStoreProductSkuBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpSellerStoreProductSku> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getSellerStoreProductId() != null, ErpSellerStoreProductSku::getSellerStoreProductId, bo.getSellerStoreProductId());
        lqw.eq(bo.getAeProductId() != null, ErpSellerStoreProductSku::getAeProductId, bo.getAeProductId());
        lqw.eq(StringUtils.isNotBlank(bo.getSkuCode()), ErpSellerStoreProductSku::getSkuCode, bo.getSkuCode());
        lqw.eq(StringUtils.isNotBlank(bo.getAeProductSkuId()), ErpSellerStoreProductSku::getAeProductSkuId, bo.getAeProductSkuId());
        lqw.like(StringUtils.isNotBlank(bo.getSkuName()), ErpSellerStoreProductSku::getSkuName, bo.getSkuName());
        lqw.eq(StringUtils.isNotBlank(bo.getSkuImage()), ErpSellerStoreProductSku::getSkuImage, bo.getSkuImage());
        lqw.eq(StringUtils.isNotBlank(bo.getImageUrlList()), ErpSellerStoreProductSku::getImageUrlList, bo.getImageUrlList());
        lqw.eq(bo.getSkuLength() != null, ErpSellerStoreProductSku::getSkuLength, bo.getSkuLength());
        lqw.eq(bo.getSkuWidth() != null, ErpSellerStoreProductSku::getSkuWidth, bo.getSkuWidth());
        lqw.eq(bo.getSkuHeight() != null, ErpSellerStoreProductSku::getSkuHeight, bo.getSkuHeight());
        lqw.eq(bo.getSkuWeight() != null, ErpSellerStoreProductSku::getSkuWeight, bo.getSkuWeight());
        lqw.eq(StringUtils.isNotBlank(bo.getSkuPrice()), ErpSellerStoreProductSku::getSkuPrice, bo.getSkuPrice());
        lqw.eq(bo.getSkuStock() != null, ErpSellerStoreProductSku::getSkuStock, bo.getSkuStock());
        lqw.eq(StringUtils.isNotBlank(bo.getSkuDiscountPrice()), ErpSellerStoreProductSku::getSkuDiscountPrice, bo.getSkuDiscountPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getSkuNationalDiscountPrice()), ErpSellerStoreProductSku::getSkuNationalDiscountPrice, bo.getSkuNationalDiscountPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getSkuPropertyIds()), ErpSellerStoreProductSku::getSkuPropertyIds, bo.getSkuPropertyIds());
        lqw.eq(StringUtils.isNotBlank(bo.getRevision()), ErpSellerStoreProductSku::getRevision, bo.getRevision());
        return lqw;
    }

    /**
     * 新增卖家在线商品SKU;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）
     */
    @Override
    public Boolean insertByBo(ErpSellerStoreProductSkuBo bo) {
        ErpSellerStoreProductSku add = BeanUtil.toBean(bo, ErpSellerStoreProductSku.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改卖家在线商品SKU;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）
     */
    @Override
    public Boolean updateByBo(ErpSellerStoreProductSkuBo bo) {
        ErpSellerStoreProductSku update = BeanUtil.toBean(bo, ErpSellerStoreProductSku.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpSellerStoreProductSku entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除卖家在线商品SKU;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public TableDataInfo<ErpSellerStoreProductSku> getSkuAndProduct(PageQuery pageQuery, QueryProductParam param) {
        Page<ErpSellerStoreProductSku> skuAndProduct = baseMapper.getSkuAndProduct(pageQuery.build(), param);
        return TableDataInfo.build(skuAndProduct);
    }

    @Override
    public Map<String,Object> getSkuPrice(Long productSkuId, String country) {
        Map<String, Object> map = new HashMap<>();
        ErpSellerStoreProductSku productSku = baseMapper.selectById(productSkuId);
        String skuPropertyIds = productSku.getSkuPropertyIds();
        Long sellerStoreProductId = productSku.getSellerStoreProductId();
        ErpSellerStoreProductExpand productExpand = productExpandMapper.selectOne(new LambdaQueryWrapper<ErpSellerStoreProductExpand>().eq(ErpSellerStoreProductExpand::getSellerStoreProductId, sellerStoreProductId));
        String absoluteQuoteMapStr = productExpand.getAbsoluteQuoteMap();
        List<Dict> absoluteQuoteMapList = JsonUtils.parseArrayMap(absoluteQuoteMapStr);
        BigDecimal skuPrice = null; // sku在线商品价格
        for (Dict dict : absoluteQuoteMapList) {
            String dictCountry = dict.getStr("shiptoCountry");
            if (country.equals(dictCountry)) {
                Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
                Double skuPriceD =(Double) absoluteQuoteMap.get(skuPropertyIds);
                skuPrice = BigDecimal.valueOf(skuPriceD);
                map.put("onLinkPrice",skuPrice);
                break;
            }
        }

        // 获取采购价
        ErpCollectProductSkuPrice bySkuCode = productSkuPriceService.getBySkuCode(productSku.getSkuCode());
        String absoluteQuoteMap = bySkuCode.getAbsoluteQuoteMap();
        Dict dict = JsonUtils.parseMap(absoluteQuoteMap);
        String purchasePrice = (String) dict.get(country);
        map.put("purchasePrice",new BigDecimal(purchasePrice));
        return map;
    }

    @Override
    public R<Object> getSellerStoreProductSkuListInfo(ErpSellerStoreProductSku sellerStoreProductSku){
        ErpSellerStoreProductSkuBo erpSellerStoreProductSkuBo = BeanUtil.copyProperties(sellerStoreProductSku, ErpSellerStoreProductSkuBo.class);
        LambdaQueryWrapper<ErpSellerStoreProductSku> lqw = buildQueryWrapper(erpSellerStoreProductSkuBo);
        List<ErpSellerStoreProductSku> skuList = baseMapper.selectList(lqw);
        if (Objects.isNull(skuList)) {
            return R.fail("未查找到信息");
        }else {
            return R.ok(skuList);
        }
    }

    @Override
    public R<Object> deletErpSellerStoreProductSkuList(List<ErpSellerStoreProductSku> sellerStoreProductSku) {
        int i = baseMapper.deleteBatchIds(sellerStoreProductSku);
        if (i > 0){
            return R.ok("删除成功");
        }else {
            return R.fail("删除失败");
        }
    }

    @Override
    public R<Object> getSellerStoreSkuAttr(Long id) {
        List<SkuInventory> sellerStoreSkuAttr = baseMapper.getSellerStoreSkuAttr(id);
        return R.ok(sellerStoreSkuAttr);
    }
}
